#!/bin/bash

timeout=300  # 最大等待60秒
count=0

ip=$1
echo "输入参数：$ip"
# 配置参数
SOURCE_DIRS=(
  /home/cys/www/data/$ip
)                    # 源目录
TARGET_DIR=/home/cys/www/data_vector_monitor/data/$ip          # 目标目录
HOURS_BACK=4                       # 回溯小时数
# 记录开始时间（自动从0开始计时）
SECONDS=0
# 定义要匹配的字符串数组
#pattern_keys=("launcher_start" "negative_systemui_start" "systemui_start" "ad_to_load" "ad_loaded" "ad_impression" "ad_clicked" "widget_show" "widget_click_detail" "widget_text_click_detail" "server_active_event")
pattern_keys=()
echo ************************begin monitor rsync************************************

while pgrep rsync > /dev/null; do
    if [ $count -ge $timeout ]; then
        echo "等待rsync超时，退出本次任务"
        exit 1
    fi

    echo "rsync正在运行，等待5秒... ($((count+5))/$timeout 秒)"
    sleep 5
    count=$((count+5))
done

# 计算并打印执行时间
duration=$SECONDS
echo "等待rsync进程时间:$duration"
echo ************************begin backup************************************
echo $(date '+%F %T')
time_regex=""
for ((i=0; i<=HOURS_BACK; i++)); do
    pattern=$(date -d "$i hours ago" +%Y-%m-%d_%H)
    if [[ -z "$time_regex" ]]; then
        time_regex="$pattern"
    else
        time_regex="$time_regex|$pattern"
    fi
done
# 记录开始时间（自动从0开始计时）
SECONDS=0
echo "正在查找包含以下时间模式的文件: $time_regex"
echo "========================================"
# 处理每个源目录
for dir in "${SOURCE_DIRS[@]}"; do
    SOURCE_DIR=$dir
    # 检查源目录是否存在
    if [ ! -d "$SOURCE_DIR" ]; then
        echo "警告：源目录 '$SOURCE_DIR' 不存在，跳过"
        continue
    fi

    # 创建目标目录
    mkdir -p "$TARGET_DIR"

    echo ""
    echo "处理目录: $SOURCE_DIR -> $TARGET_DIR"
    echo "----------------------------------------"

    copied_count=0
    total_count=0
    # 使用find命令递归查找并拷贝文件
    while IFS= read -r -d '' file; do
      if [[ -f "$file" ]]; then
            # 获取相对于源目录的路径（去掉SOURCE_DIR前缀）
            relative_path="${file#$SOURCE_DIR/}"
            relative_path="${relative_path#/}"  # 去掉开头的斜杠
            ((total_count++))
            # 创建目标子目录
            if [[ -n "$relative_path" && "$relative_path" != "$(basename "$file")" ]]; then
                target_subdir="$TARGET_DIR/$(dirname "$relative_path")"
                mkdir -p "$target_subdir"
            else
                target_subdir="$TARGET_DIR"
            fi
            #echo "relative_path:"$relative_path
            #echo "target_subdir:"$target_subdir
            # 拷
            filename=$(basename "$file")
      target_file=$target_subdir/$filename
      #echo "filename:"$filename"---target_file:"$target_file
      need_copy=0
      is_contain_eventid=0
      origin_file_count=0
      #匹配特定字符串
      if [[ ${#pattern_keys[@]} > 0 ]]; then
          for pattern_key in "${pattern_keys[@]}"; do
              if [[ "$filename" == *"$pattern_key"* ]]; then
                  is_contain_eventid=1
                  break
              fi
          done
      else
         is_contain_eventid=1
      fi
      #echo "filename:$filename--is_contain_eventid:$is_contain_eventid"
      if [[ "$is_contain_eventid" == 1 ]]; then
           if [[ ! -f "$target_file" ]]; then
               need_copy=1
           else
               # origin_file_count=$(wc -l < "$file")
               #target_file_count=$(wc -l < "$target_file")
               #if [[ $origin_file_count != $target_file_count ]]; then
               #    need_copy=1
               #fi
               echo "file:"$file"--origin_file_count:"$origin_file_count"--target_file_count:"$target_file_count"--need_copy:"$need_copy
           fi
      fi
      if [[ "$need_copy" == 1 ]]; then

         if cp -v "$file" "$target_subdir/"; then
            ((copied_count++))
            time_sleep=$((origin_file_count/10000))
            echo "✓ 已拷贝 copyed: $relative_path--origin_file_count:$origin_file_count--time_sleep:$time_sleep"
            if [[ HOURS_BACK > 5 ]]; then
                #echo "*********sleep*****************"
                sleep $time_sleep
              sleep 2
            fi
         else
            echo "✗ 拷贝失败: $relative_path"
         fi
      fi
      if [[ HOURS_BACK > 5 ]]; then
          i=1
          sleep 0.5
      fi
      fi
    done < <(find "$SOURCE_DIR" -type f -regextype posix-extended -regex ".*($time_regex).*" -print0)

    echo "完成 $SOURCE_DIR: 总共遍历 $total_count 个文件，成功拷贝 $copied_count 个文件"
done
# 计算并打印执行时间
duration=$SECONDS
echo ""
echo "========================================"
echo "所有目录处理完成！脚本执行总时长: $duration 秒"
echo ***********************finish backup************************************
echo $(date '+%F %T')
